const todoState ={
  todos:JSON.parse(localStorage.getItem("todo"))||[],//源数据
  showTodos:JSON.parse(localStorage.getItem("todo"))||[]
}

export function todoReducer(state=todoState,action){
  console.log(action)
  switch (action.type){
    case "ADDTODO":
      var flag = false;
      state.todos.forEach(element=>{
        if(element.context===action.todo.context){
          flag = true;
        }
      })

      if(flag){
        alert("不能重复添加todo");
        return state;
      }

      state.todos.push(action.todo);
      localStorage.setItem("todo",JSON.stringify(state.todos))
      return{
        todos:[...state.todos],
        showTodos:[...state.todos]
      }
    case "CHANGESTATUS":
      state.todos.forEach((element)=>{
        if(element.context === action.todo.context){
          element.status = action.checked?"FINISHED":"PENDDING"
        }
      })
      localStorage.setItem("todo",JSON.stringify(state.todos))
      return{
        todos:[...state.todos],
        showTodos:[...state.todos]
      }
    case "all":
      return {
        todos:[...state.todos],
        showTodos:[...state.todos]
      }
    case "pendding":
      state.showTodos = [];
      state.todos.forEach((element)=>{
        if(element.status === "PENDDING"){
          state.showTodos.push(element)
        }
      })

      return{
        todos:state.todos,
        showTodos:[...state.showTodos]
      }
    case "fininshed":
      state.showTodos = [];
      state.todos.forEach((element)=>{
        if(element.status === "FINISHED"){
          state.showTodos.push(element)
        }
      })
      return{
        todos:state.todos,
        showTodos:[...state.showTodos]
      }
    case "delete":
      var tempIndex1 = state.todos.findIndex((element)=>{
        return element.context===action.todo.context;
      })
      var tempIndex2 = state.showTodos.findIndex((element)=>{
        return element.context===action.todo.context;
      })

      if(tempIndex1!=-1){
        state.todos.splice(tempIndex1,1);
      }

      if(tempIndex2!=-1){
        state.showTodos.splice(tempIndex2,1);
      }

      return{
        todos:[...state.todos],
        showTodos:[...state.showTodos]
      }

    default:
      return state;
  }
}